let enumIdList = new Array();

/**
 * zmn文章模块-文章编辑
 * 文件命名格式：zmn.模块.表/功能.jas
 * @author heguanghua
 * @since 2018/10/18
 */
layui.define(['form', 'layedit', 'laydate'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;
    let layedit = layui.layedit;
    let laydate = layui.laydate;
    let index;


    form.verify({
        minSort: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (value < 1000) {
                return "排序号不能小于1000";
            }
        }, isPositiveNumber: function (value, item) {
            if (!/^[0-9]+$/.test(value)) {
                return "排序值只能是正整数";
            }
        }, tariffName: function (value) {
            if (!/^[A-Za-z0-9\u4e00-\u9fa5]+$/.test(value)) {
                return "计价器名称只能输入字母、数字、汉字";
            }
        }
    });
    if(json.servProductVO.productId > 0){
        $('#channelId').attr("disabled",true);
    }
    zmnLayUtil.layFormVerify(form);
    form.render(null, "zmn-form");

    // 分类下拉框联动
    zmnProduct.laySelectSpecial(form, "/showProduct/listChilds.action", "/showProduct/listCateChilds.action", "/showProduct/listAttrChilds.action", "servCategId", "categOneId", "categId", "attrId");

    let optionHtml = loadProductCateg(json.attrList);
    $("#attrId").html(optionHtml);
    // 提交
    form.on('submit(zmn-form-submit)', function (obj) {
        let data = obj.field;
        // 获取业务类型和视频类型的复选框数据以”,“号分隔
        let bizType = new Array()
        $('#bizType input[type=checkbox]:checked').each(function () {
            bizType.push($(this).val());
        });

        if (bizType.length == 0) {
            layer.msg("业务类型不能为空", {"icon": 2});
            return false;
        }
        data.bizType = bizType.join("$");
        // 计价器
        if (!data.tariffStatus) {
            layer.msg("计价器状态必选");
            return false;
        }

        let priorityFrist = data.priorityFrist;
        let prioritySecond = data.prioritySecond;
        let priorityThird = data.priorityThird;
        let priorityFour = data.priorityFour;

        // 非默认产品才有转单优先级
        if (data.defaultType != 2) {
            if ((zmnUtil.isEmptyNull(priorityFrist) || priorityFrist <= 0)
                || (zmnUtil.isEmptyNull(prioritySecond) || prioritySecond <= 0)
                || (zmnUtil.isEmptyNull(priorityThird) || priorityThird <= 0)
                || (zmnUtil.isEmptyNull(priorityFour) || priorityFour <= 0)) {
                layer.msg("转单优先级平台不能为空", {"icon": 2});
                return false;
            }

            if (priorityFrist == prioritySecond || priorityFrist == priorityThird || priorityFrist == priorityFour
                || prioritySecond == priorityThird || prioritySecond == priorityFour || priorityThird == priorityFour) {
                layer.msg("转单优先级平台不能重复", {"icon": 2});
                return false;
            }

            if (zmnUtil.isEmptyNull(data.ficoCtegId) || data.ficoCtegId <= 0) {
                layer.msg("绩效分类不能为空", {"icon": 2});
                return false;
            }

            if (zmnUtil.isEmptyNull(data.unit) || data.unit <= 0) {
                layer.msg("单位不能为空", {"icon": 2});
                return false;
            }

            if (zmnUtil.isEmptyNull(data.priceStatement)) {
                layer.msg("一口价说明不能为空", {"icon": 2});
                return false;
            }
        }
        //解决默认产品
        data.defaultType = data.productType == 2 ? 1 : data.defaultType
        //暂时还不知道有啥作用
        let attrEnumArr = new Array();
        enumIdList.forEach(x => {
            let enumId = $('input[name="' + x + 'name"]:checked').val();
            if (zmnUtil.isNotNull(enumId)) {
                attrEnumArr.push(x + "&" + enumId);
            }
        })
        data.enumIds = attrEnumArr.join(",");


        let url = "/showProduct/addEdit.action";
        $.ajax({
            async: false,
            type: "POST", url: url,
            contentType: "application/json", dataType: "json", data: JSON.stringify(data),
            beforeSend: function () {
                index = layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            success: function (json) {
                if (json.status == 200) {
                    layer.msg("操作成功", {time: 1000}, () => {
                        zmnLayUtil.closeThisIframe(parent);
                    });
                } else {
                    layer.msg(json.message, {"icon": 2});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            complete: function () {
                layer.close(index);
            }
        })

        return false;
    });
    form.on('radio(defaultType)', function (obj) {
        // 如果为前台默认产品，则故障分组等不显示，反之则显示
        if (obj.value == 1) {
            $("#faultGroupDiv").show();
            $("#ficoCtegDiv").show();
            $("#unitDiv").show();
            $("#priorityDiv").show();
            $("#priceStatementDiv").show();

            $('#upStatusId').attr("disabled", true);
            $("input[name='status'][value='1']").prop('checked', true);
            form.render(null);
        } else {
            $("#faultGroupDiv").hide();
            $("#ficoCtegDiv").hide();
            $("#unitDiv").hide();
            $("#priorityDiv").hide();
            $("#priceStatementDiv").hide();

            // 新增默认产品时 产品可以选择上下架，非默认产品新增只能选择下架
            $('#upStatusId').attr("disabled", false);
            $("input[name='status'][value='1']").prop('checked', true);
            form.render(null);
        }
    });

    //对外暴露的接口
    exports('product_show_edit_js', {});
});

var zmnProduct = {
    /**
     * 多级下拉框联动
     * @param form layui.form
     * @param url1 selectOneId请求下级数据的url，返回数据格式 [[value,text], [value,text], [value,text], …]
     * @param url1 selectTwoId请求下级数据的url，返回数据格式 [[value,text], [value,text], [value,text], …]
     * @param selectOneId 第1级select的ID，不含#号
     * @param selectTwoId 第2级select的ID，不含#号
     * @param selectThrId 第3级select的ID，不含#号，如无第3级则两级联动
     */
    laySelectSpecial: function (form, url1, url2, url3, selectOneId, selectTwoId, selectThrId, selectFourId) {
        let $ = layui.$;
        let servCategId;
        let categOneId;
        form.on("select(" + selectOneId + ")", function (obj) {
            if (zmnUtil.isNull(obj) || obj.value == 0) {
                return layer.alert("请选择！");
            }
            servCategId = obj.value;
            $.ajax({
                type: "GET", url: url1,
                dataType: "json", data: {parentId: servCategId},
                success: function (items) {
                    var optionHtml = '<option value="">请选择</option>';
                    for (var i = 0; i < items.length; i++) {
                        optionHtml += '<option value="' + items[i][0] + '">' + items[i][1] + '</option>';
                    }
                    $("#" + selectTwoId).html(optionHtml);
                    $("#" + selectThrId).html('<option value="">请选择</option>');
                    $("#" + selectFourId).html('<option value="">请选择</option>');
                    form.render("select");
                }
            });
        });
        if (zmnUtil.isEmptyNull(selectThrId)) {
            return;
        }
        ;

        form.on("select(" + selectTwoId + ")", function (obj) {
            if (zmnUtil.isNull(obj) || obj.value == 0) {
                return layer.alert("请选择！");
            }
            categOneId = obj.value;
            servCategId = $('#servCategId').val();
            ;
            $.ajax({
                type: "GET", url: url2,
                dataType: "json", data: {categOneId: obj.value, servCategId: servCategId},
                success: function (items) {
                    let optionHtml = '<option value="">请选择</option>';
                    for (var i = 0; i < items.length; i++) {
                        optionHtml += '<option value="' + items[i][0] + '">' + items[i][1] + '</option>';
                    }
                    $("#" + selectThrId).html(optionHtml);
                    $("#" + selectFourId).html('<option value="">请选择</option>');
                    form.render("select");
                }
            });
        });

        if (zmnUtil.isEmptyNull(selectFourId)) {
            return;
        }
        ;

        form.on("select(" + selectThrId + ")", function (obj) {
            if (zmnUtil.isNull(obj) || obj.value == 0) {
                return layer.alert("请选择！");
            }
            $.ajax({
                type: "GET", url: url3,
                dataType: "json", data: {categId: obj.value, categOneId: categOneId},
                success: function (items) {
                    let optionHtml = loadProductCateg(items);
                    $("#" + selectFourId).html(optionHtml);
                    form.render("radio");
                    form.render("checkbox");
                }
            });
        });
    },
}

function loadProductCateg(items) {
    //渲染一级分类数据
    if (zmnUtil.isNull(items)) {
        return "";
    }
    let produHtml = "";
    for (let i = 0; i < items.length; i++) {
        enumIdList.push(items[i].attrId);
        produHtml += '<div class="layui-form-item" pane=""><label class="layui-form-label">' + items[i].name + '：</label>' +
            '<div class="layui-input-block">' + formatterCheckboxValue(items[i].baseCategoryAttributeEnumList, items[i].attrId) + '</div></div>';
    }
    return produHtml;
}

//渲染二级分类数据
function formatterCheckboxValue(baseCategoryAttributeEnumList, attrId) {
    let name = attrId + 'name';
    let checkboxHtml = '<input type="radio" name="' + name + '" lay-skin="primary" value="' + attrId + '" title="无属性值" />';
    if (zmnUtil.isNotNull(json.servProductVO.sequence) && json.servProductVO.sequence.indexOf(attrId) != -1) {
        checkboxHtml = '<input type="radio" name="' + name + '" checked lay-skin="primary" value="' + attrId + '" title="无属性值" />';
    }
    for (let i = 0; i < baseCategoryAttributeEnumList.length; i++) {
        if (zmnUtil.isNotNull(json.servProductVO.sequence) && json.servProductVO.sequence.indexOf(baseCategoryAttributeEnumList[i].enumId) != -1) {
            checkboxHtml += '<input type="radio" name="' + name + '" lay-skin="primary" checked value="' + baseCategoryAttributeEnumList[i].enumId + '" title="' + baseCategoryAttributeEnumList[i].enumValue + '" />'
        } else {
            checkboxHtml += '<input type="radio" name="' + name + '" lay-skin="primary" value="' + baseCategoryAttributeEnumList[i].enumId + '" title="' + baseCategoryAttributeEnumList[i].enumValue + '" />'
        }
    }
    return checkboxHtml;
}

// 图文复用

function copyFromCategory(type, productId) {
    let title = "复用产品描述";
    if (type == 2) {
        title = "复用图片视频";
    } else if (type == 3) {
        title = "复用产品保障";
    }

    layer.open({
        type: 2,
        title: title,
        area: ['90%', '80%'],
        content: '/showProduct/categorylist.action?type=' + type + "&productId=" + productId
    });
}